<template>
  <!-- 竣工项目归档资料 -->
  <base-breadcrumb class="archiveDoc-container">
    <searchData
      :searchData="searchArr"
      @search="handleSearch"
      @autoSelected="handleProjectAuto"
    ></searchData>
    <a-card :bordered="false">
      <!-- <title-name title="竣工项目归档" /> -->
      <div class="pub-table-action-btn">
        <!-- <excel v-btnPermission="'oa_009_exp_01'" ref="exportBtn" :fileName="exportFileName" is-click-generate="false">
          <a-button slot="excelBtn" type="primary" :loading="loadingState.isExport" @click="handleExport"
            >导出</a-button
          >
        </excel> -->
      </div>
      <list-table
        ref="table"
        row-key="id"
        :columns="columns"
        :request="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        :export-permission="{ select: 'oa_009_exp_01', all: 'oa_009_exp_01' }"
        :export-config="{ use: true, select: `${exportFileName}`, all: `${exportFileName}` }"
      >
        <template
          slot="actualArchiveTime"
          slot-scope="text"
        >
          {{ text || '—' }}
        </template>
        <template
          slot="ifCheckArchive"
          slot-scope="text, record"
        >
          <!-- 当资料审核状态为通过时，为已归档，其余情况为未归档 -->
          <span v-if="record.archiveDataStatus == 2">是</span>
          <span
            v-else
            style="color: red"
          >否</span>
        </template>
        <template
          slot="ifOver"
          slot-scope="text"
        >
          <span
            v-if="text"
            style="color: red"
          >是</span>
          <span v-else>否</span>
        </template>
        <template
          slot="ifArchiveExtendedApply"
          slot-scope="text"
        >
          <span
            v-if="text"
            style="color: red"
          >是</span>
          <span v-else>否</span>
        </template>
        <template
          slot="archiveDataStatus"
          slot-scope="text, record"
        >
          <status-display
            :statusCode="text"
            isApproval
          />
        </template>
        <template
          slot="action"
          slot-scope="text, record"
        >
          <MoreButton>
            <a
              v-btnPermission="'oa_009_loo_02'"
              @click="handleUpdate(record, 'look')"
            >查看</a>
            <a
              v-btnPermission="'oa_009_edi_03'"
              v-if="record.archiveDataStatus == 0 || record.archiveDataStatus == 3"
              @click="handleUpdate(record, 'edit')"
            >编辑</a>
            <a
              v-if="record.archiveDataStatus && record.archiveDataStatus != 0"
              @click="handleUpdate(record, 'auditInfo')"
            >审批信息</a>
          </MoreButton>
        </template>
      </list-table>
    </a-card>
  </base-breadcrumb>
</template>

<script>
// import { STable } from '@/components' // 表格
import SelectProject from '@/components/Select/SelectProject' // 项目
import { packageConfirm } from '@/utils/baseAction.js'
import StatusDisplay from '@/components/StatusDisplay'
import { getArchiveDocList } from '@/api/office/archiveManage/archiveDoc.js'
import { STATUS_MAP_Number } from '@/config/businessConfig.js'
import Vue from 'vue'
import SelectSubCompany from '@/components/Select/SelectSubCompany'
import OrgTreeSelect from '@/components/OrgTreeSelect'

const userInfo = Vue.getAcloudProvider().getUserInfo()

const searchArr = [
  // {
  //   name: '所属分公司',
  //   valueKey: 'branchOrgId',
  //   type: SelectSubCompany,
  //   autoSelected: userInfo?.currentPost?.code !== 'CO' // 分公司级别的岗位，自动选择
  // },
  {
    name: '所属单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
  },
  // {
  //   name: '所属分公司',
  //   valueKey: 'branchOrgId',
  //   type: SelectSubCompany,
  //   autoSelected: userInfo?.currentPost?.code !== 'CO' // 分公司级别的岗位，自动选择
  // },
  // {
  //   name: '项目名称',
  //   valueKey: 'projectId',
  //   type: SelectProject,
  //   onlyCurrentPd: true,
  //   needLink: false,
  //   autoSelected: userInfo?.currentPost?.code === 'PD' // 项目级别的岗位，自动选择
  // },
  {
    name: '归档年度',
    value: 'archiveYear',
    type: 'year',
    placeholder: '请选择',
    setInitValue: true,
    initValue: `${new Date().getFullYear()}`,
    attr: {
      allowClear: false
    }
  }
]
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '分公司',
    dataIndex: 'branchOrgName'
  },
  {
    title: '项目',
    dataIndex: 'projectName',
    ellipsis: true
  },
  {
    title: '开工日期',
    dataIndex: 'startWorkingTime'
  },
  {
    title: '竣工日期',
    dataIndex: 'completionTime'
  },
  {
    title: '计划归档日期',
    dataIndex: 'archiveTime'
  },
  {
    title: '实际归档日期',
    dataIndex: 'actualArchiveTime',
    scopedSlots: { customRender: 'actualArchiveTime' }
  },
  {
    title: '是否已归档',
    dataIndex: 'ifCheckArchive',
    scopedSlots: { customRender: 'ifCheckArchive' }
  },
  {
    title: '是否已超期',
    dataIndex: 'ifOver',
    scopedSlots: { customRender: 'ifOver' }
  },
  {
    title: '是否申请延期归档',
    dataIndex: 'ifArchiveExtendedApply',
    scopedSlots: { customRender: 'ifArchiveExtendedApply' }
  },
  {
    title: '归档资料状态',
    dataIndex: 'archiveDataStatus',
    scopedSlots: { customRender: 'archiveDataStatus' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    // STable,
    StatusDisplay
  },
  data() {
    return {
      exportFileName: '',
      loadingState: {
        isAdd: false,
        isExport: false
      },
      searchArr,
      columns: columns,
      queryParam: {}
    }
  },
  methods: {
    handleProjectAuto(val) {
      this.queryParam = {
        ...this.queryParam,
        projectId: val
      }
      if (userInfo?.currentPost?.code === 'PD') {
        this.refreshTable()
      }
    },
    /**
     * 导出
     */
    async handleExport() {
      try {
        if (this.loadingState.isExport) return
        this.loadingState.isExport = true
        const res = await this.loadData({ needCount: false })
        if (!res.data.length) {
          this.$message.warning('无导出数据')
          this.loadingState.isExport = false
          return
        }
        this.loadingState.isExport = false
        const columns = this.columns.filter((item) => item.dataIndex !== 'index' && item.dataIndex !== 'action')
        const convertKeys = ['ifOver', 'ifArchiveExtendedApply']
        let branchComName = ''
        const list = (res.data || []).map((item) => {
          if (!branchComName) {
            branchComName = item.branchOrgName
          }
          convertKeys.forEach((key) => {
            item[key] = item[key] ? '是' : '否'
          })
          // 当资料审核状态为通过时，为已归档，其余情况为未归档
          item.ifCheckArchive = item.archiveDataStatus == 2 ? '是' : '否'
          item.archiveDataStatus = STATUS_MAP_Number[item.archiveDataStatus]?.label
          return item
        })
        this.exportFileName = `${branchComName}${this.queryParam.archiveYear || new Date().getFullYear()}年度归档台账`
        this.$refs.exportBtn.generateExcel(list, { columns })
      } catch (e) {
        console.error(e)
        this.loadingState.isExport = false
      }
    },
    /**
     * 处理数据的相关操作（增删改查）
     */
    handleUpdate(data, pageType) {
      const commonHandler = () => {
        this.$router.push({
          path: '/conference/archiveManage/archiveDoc/update',
          query: {
            id: data.id || '',
            pageType: pageType,
            archiveTime: data.archiveTime || '',
            projectId: data.projectId || ''
          }
        })
      }
      const actionMap = {
        add: async () => {
          try {
            if (this.loadingState.isAdd) return
            this.loadingState.isAdd = true
            await accessIfDelayApply()
            commonHandler()
            this.loadingState.isAdd = false
          } catch (e) {
            console.error(e)
            this.loadingState.isAdd = false
          }
        },
        edit: commonHandler,
        look: commonHandler,
        auditInfo: () => {
          this.$bus.$emit('showApprovalDetailsDialog', data.id)
        },
        delete: async () => {
          packageConfirm({
            callback: async () => {
              const res = await deleteDelayApply({ id: data.id })
              this.$message.success('删除成功')
              this.refreshTable()
            }
          })
        }
      }
      actionMap[pageType] && actionMap[pageType]()
    },
    handleSearch(val = {}) {
      this.queryParam = {
        ...val
      }
      this.refreshTable()
    },
    refreshTable() {
      this.$refs.table.refresh(true)
    },
    async loadData(parameter) {
      const requestParameters = Object.assign({}, { ...parameter }, { query: { ...this.queryParam, archiveYear: this.queryParam.archiveYear || new Date().getFullYear() } })
      return getArchiveDocList(requestParameters)
    }
  }
}
</script>

<style>
</style>
